package tutorial.main.control;


import java.util.HashMap;
import java.util.Iterator;

import tutorial.main.control.location.LocationFinder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ConectivityListener
{
	private NetChangeBroadcastReciver receiver;
	private boolean listening;
	private boolean conectado;
	private Bundle netInfo;
	
	private HashMap<Handler, Integer> mHandlers = new HashMap<Handler, Integer>();
	private Context context;
	
	public ConectivityListener() 
	{
		receiver = new NetChangeBroadcastReciver();
	}
	
	public synchronized void RegisterListening(Context context) 
	{
		if (!listening) 
		{
			this.context = context;
			IntentFilter filter = new IntentFilter();
			filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
			context.registerReceiver(receiver, filter);
			listening = true;
		}
	}
	
	public synchronized void UnregisterListening() 
	{
		if (listening) 
		{
			context.unregisterReceiver(receiver);
			context = null;
			listening = false;
		}
	}
	
	public synchronized Bundle getNetworkInfo()
	{
		return this.netInfo; 	
	}
	
	public void RegisterHandler(Handler target, int what) 
	{
		mHandlers.put(target, what);
	}

	public void UnregisterHandler(Handler target) 
	{
		mHandlers.remove(target);
	}	
	
	public boolean isConnected() 
	{
		return conectado;
	}
	
	private class NetChangeBroadcastReciver extends BroadcastReceiver
	{
	
		private NetChangeService ncservice;
	    // Me conecto con el servicio
		private ServiceConnection mConnection;
		
		@Override
		public void onReceive(Context context, Intent intent) 
		{
			Log.v("NetChangeBroadcastReciver","Salto el Trigger");
			String action = intent.getAction();
		
			if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
			{
				boolean connectivity = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
				
				conectado = connectivity;
				// LOGEO
				Log.v("NetChangeBroadcastReciver","Hay Red: "+connectivity);
		
				// RECOPILO INFO
				NetworkInfo mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);			
				String info = "Tipo: "+mNetworkInfo.getTypeName()+" - "+mNetworkInfo.getSubtypeName();
	
				// Muesto el cambio de estado en el layuot
				//SConfig.getSingleton().CambiarPanelConexion(noConnectivity,info);//TODO: Kill Singleton
				
				// Guardo la hora y fecha
				long cuando = System.currentTimeMillis();
				
				// AVISO AL SERVICE DEL CAMBIO DE ESTADO
				// Esto es para pasar muchos datos en un objeto !!
				netInfo = new Bundle();
				netInfo.putString("Info",info);
				Log.v("BroadcastReciver","No Conectado?:"+connectivity);
				netInfo.putBoolean("conectado",connectivity);
				netInfo.putLong("fecha",cuando);
				netInfo.putString("reason",mNetworkInfo.getReason());
				netInfo.putString("subnet",mNetworkInfo.getSubtypeName());
				netInfo.putString("nettype",mNetworkInfo.getTypeName());
				
				// FLACO !! CAMBIO LA CONEXION, ENCARGATE DE AVISAR !!
				// Hay que tener en cuenta que el servicio este activo
				Iterator<Handler> it = mHandlers.keySet().iterator();
				while (it.hasNext()) 
				{
					Handler target = it.next();
					Message message = Message.obtain(target, mHandlers.get(target));
					target.sendMessage(message);
				}
				
			}
		}
		
		
	}

}